import os

def merge_txt_files(directory, output_file, exclude_files):
    """整合指定目录及其子目录中的所有 .txt 文件内容，排除指定文件"""
    with open(output_file, 'w', encoding='utf-8') as outfile:
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith('.txt') and file not in exclude_files:
                    file_path = os.path.join(root, file)
                    try:
                        # 尝试以 utf-8 读取文件
                        with open(file_path, 'r', encoding='utf-8') as infile:
                            outfile.write(f"内容来自: {file_path}\n")
                            outfile.write(infile.read())
                            outfile.write("\n" + "="*50 + "\n")
                        print(f"已整合: {file_path}")
                    except UnicodeDecodeError:
                        try:
                            # 如果 utf-8 失败，尝试使用 GBK 编码
                            with open(file_path, 'r', encoding='gbk') as infile:
                                outfile.write(f"内容来自: {file_path}\n")
                                outfile.write(infile.read())
                                outfile.write("\n" + "="*50 + "\n")
                            print(f"已整合 (GBK): {file_path}")
                        except UnicodeDecodeError:
                            try:
                                # 如果 GBK 失败，尝试使用 ISO-8859-1 编码
                                with open(file_path, 'r', encoding='iso-8859-1') as infile:
                                    outfile.write(f"内容来自: {file_path}\n")
                                    outfile.write(infile.read())
                                    outfile.write("\n" + "="*50 + "\n")
                                print(f"已整合 (ISO-8859-1): {file_path}")
                            except Exception as e:
                                print(f"无法读取 {file_path}: {e}")

if __name__ == "__main__":
    # 指定要整合的目录
    target_directory = os.path.dirname(__file__)  # 当前脚本所在目录
    output_file = os.path.join(target_directory, 'merged_results.txt')
    exclude_files = ['数据集信息.txt', 'merged_results.txt']  # 排除自身和数据集信息文件
    print(f"开始整合目录: {target_directory}")
    merge_txt_files(target_directory, output_file, exclude_files)
    print(f"整合完成! 结果已保存到: {output_file}")
